package com.atguigu.realtime.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.realtime.app.BaseAppV1;
import com.atguigu.realtime.bean.TrafficHomeDetailPageViewBean;
import com.atguigu.realtime.common.Constant;
import com.atguigu.realtime.util.AtguiguUtil;
import com.atguigu.realtime.util.FlinkSinkUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.ProcessAllWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;

/**
 * @Author lzc
 * @Date 2022/5/28 9:03
 */
public class Dws_03_TrafficHomeDetailPageViewBean extends BaseAppV1 {
    public static void main(String[] args) {
        new Dws_03_TrafficHomeDetailPageViewBean().init(3003,
                                                        2,
                                                        "Dws_03_TrafficHomeDetailPageViewBean",
                                                        Constant.TOPIC_DWD_TRAFFIC_PAGE
        );
    }
    
    @Override
    protected void handle(StreamExecutionEnvironment env,
                          DataStreamSource<String> stream) {
        // 1. 解析数据, 找到每天的第一个首页的访问记录和详情页的访问记录
        SingleOutputStreamOperator<TrafficHomeDetailPageViewBean> beanStream = findUv(stream);
        // 2. 开窗聚合
        SingleOutputStreamOperator<TrafficHomeDetailPageViewBean> aggregatedStream = windowAndAggregate(beanStream);
        
        // 3. 数据写出到clickhouse中
        writeToClickHouse(aggregatedStream);
        
    }
    
    private void writeToClickHouse(SingleOutputStreamOperator<TrafficHomeDetailPageViewBean> stream) {
        stream.addSink(FlinkSinkUtil.getClickHouseSink(Constant.CLICKHOUSE_DB,
                                                       "dws_traffic_page_view_window",
                                                       TrafficHomeDetailPageViewBean.class
        ));
        
    }
    
    private SingleOutputStreamOperator<TrafficHomeDetailPageViewBean> windowAndAggregate(
        SingleOutputStreamOperator<TrafficHomeDetailPageViewBean> beanStream) {
        return beanStream
            .windowAll(TumblingEventTimeWindows.of(Time.seconds(5)))
            .reduce(
                new ReduceFunction<TrafficHomeDetailPageViewBean>() {
                    @Override
                    public TrafficHomeDetailPageViewBean reduce(TrafficHomeDetailPageViewBean b1,
                                                                TrafficHomeDetailPageViewBean b2) throws Exception {
                        b1.setHomeUvCt(b1.getHomeUvCt() + b2.getHomeUvCt());
                        b1.setGoodDetailUvCt(b1.getGoodDetailUvCt() + b2.getGoodDetailUvCt());
                        
                        return b1;
                    }
                },
                new ProcessAllWindowFunction<TrafficHomeDetailPageViewBean, TrafficHomeDetailPageViewBean, TimeWindow>() {
                    @Override
                    public void process(Context ctx,
                                        Iterable<TrafficHomeDetailPageViewBean> elements,
                                        Collector<TrafficHomeDetailPageViewBean> out) throws Exception {
                        String stt = AtguiguUtil.toDateTime(ctx.window().getStart());
                        String edt = AtguiguUtil.toDateTime(ctx.window().getEnd());
                        
                        TrafficHomeDetailPageViewBean bean = elements.iterator().next();
                        bean.setStt(stt);
                        bean.setEdt(edt);
                        bean.setTs(System.currentTimeMillis());
                        out.collect(bean);
                    }
                }
            
            
            );
    }
    
    private SingleOutputStreamOperator<TrafficHomeDetailPageViewBean> findUv(DataStreamSource<String> stream) {
        return stream
            .map(JSON::parseObject)
            .filter(obj -> {
                String pageId = obj.getJSONObject("page").getString("page_id");
                return "home".equals(pageId) || "good_detail".equals(pageId);
            })
            .assignTimestampsAndWatermarks(
                WatermarkStrategy
                    .<JSONObject>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                    .withTimestampAssigner((obj, ts) -> obj.getLong("ts"))
            )
            .keyBy(obj -> obj.getJSONObject("common").getString("mid"))
            .process(new KeyedProcessFunction<String, JSONObject, TrafficHomeDetailPageViewBean>() {
                
                private ValueState<String> homeState;
                private ValueState<String> goodDetailState;
                
                @Override
                public void open(Configuration parameters) throws Exception {
                    homeState = getRuntimeContext().getState(new ValueStateDescriptor<String>("homeState", String.class));
                    goodDetailState = getRuntimeContext().getState(new ValueStateDescriptor<String>("goodDetailState", String.class));
                    
                }
                
                @Override
                public void processElement(JSONObject obj,
                                           Context ctx,
                                           Collector<TrafficHomeDetailPageViewBean> out) throws Exception {
                    
                    
                    long homeUvCt = 0L;
                    long goodDetailUvCt = 0L;
                    Long ts = obj.getLong("ts");
                    String today = AtguiguUtil.toDate(ts);
                    
                    String pageId = obj.getJSONObject("page").getString("page_id");
                    
                    if ("home".equals(pageId) && !today.equals(homeState.value())) {
                        // 当天的第一个home
                        homeUvCt = 1L;
                        homeState.update(today);
                        
                    } else if ("good_detail".equals(pageId) && !today.equals(goodDetailState.value())) {
                        goodDetailUvCt = 1L;
                        goodDetailState.update(today);
                    }
                    
                    // 这两个ct只要有一个不是0, 就是当天的独立访客数
                    if (homeUvCt + goodDetailUvCt == 1) {
                        TrafficHomeDetailPageViewBean bean = new TrafficHomeDetailPageViewBean("", "",
                                                                                               homeUvCt, goodDetailUvCt,
                                                                                               ts
                        );
                        out.collect(bean);
                    }
                }
            });
    }
}
/*
统计首页的独立访客数和详情页的独立访客数

1. 数据源 dwd 页面日志

2. 过滤: 首页和详情页
      page_id  home or  good_detail
      
3. map
    如果是首页
    
       homeCt = 1
       .. = 0
     如果是详情
       detailCt = 1
       ..0
 
4. 开窗聚合

5. 写出到clickhouse中




 */